from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.utils import timezone
from .models import Experiment, ExperimentStep
import requests
import json
import os


@login_required
def home_view(request):
    """主页视图，显示机械臂介绍和功能入口"""
    return render(request, 'experiment/home.html')


@login_required
def structure_view(request):
    """机械臂内部构造视图，显示机械臂内部构造详情"""
    return render(request, 'experiment/structure.html')


@login_required
def experiment_guide_view(request):
    """实验指南视图，显示机械臂实验须知"""
    return render(request, 'experiment/guide.html')


@login_required
def experiment_platform_view(request):
    """实验平台视图，用于进行机械臂实验"""
    # 检查是否有正在进行的实验
    active_experiment = Experiment.objects.filter(
        user=request.user, 
        status__in=['pending', 'in_progress']
    ).first()
    
    # 如果没有活跃实验，创建一个新的
    if not active_experiment:
        active_experiment = Experiment.objects.create(
            user=request.user,
            status='in_progress',
            current_step=1
        )
        # 创建第一个实验步骤记录
        ExperimentStep.objects.create(
            experiment=active_experiment,
            step_number=1
        )
    
    context = {
        'experiment': active_experiment,
    }
    return render(request, 'experiment/platform.html', context)


@login_required
def experiment_step_view(request, experiment_id, step):
    """处理实验步骤的视图"""
    experiment = get_object_or_404(Experiment, id=experiment_id, user=request.user)
    
    # 确保步骤顺序正确
    if experiment.current_step != step:
        messages.error(request, '请按照顺序完成实验步骤！')
        return redirect('experiment_platform')
    
    # 获取或创建当前步骤记录
    step_record, created = ExperimentStep.objects.get_or_create(
        experiment=experiment, 
        step_number=step
    )
    
    # 如果是POST请求，表示用户提交了当前步骤
    if request.method == 'POST':
        # 完成当前步骤
        step_record.is_completed = True
        step_record.end_time = timezone.now()
        step_record.save()
        
        # 更新实验状态
        if step < 5:  # 不是最后一步
            experiment.current_step = step + 1
            experiment.save()
            
            # 创建下一步的记录
            ExperimentStep.objects.create(
                experiment=experiment,
                step_number=step + 1
            )
            messages.success(request, f'步骤 {step} 完成！请继续进行下一步操作。')
        else:  # 完成全部实验
            experiment.status = 'completed'
            experiment.current_step = 5
            experiment.end_time = timezone.now()
            experiment.success = True
            experiment.save()
            messages.success(request, '恭喜！您已成功完成全部实验。')
        
        return redirect('experiment_platform')
    
    context = {
        'experiment': experiment,
        'step': step,
        'step_record': step_record,
    }
    return render(request, f'experiment/step_{step}.html', context)


@login_required
def experiment_history_view(request):
    """实验历史记录视图"""
    experiments = Experiment.objects.filter(user=request.user).order_by('-start_time')
    context = {
        'experiments': experiments,
    }
    return render(request, 'experiment/history.html', context)


@login_required
def experiment_detail_view(request, experiment_id):
    """实验详情视图，显示实验的详细记录"""
    experiment = get_object_or_404(Experiment, id=experiment_id, user=request.user)
    steps = experiment.steps.all().order_by('step_number')
    
    context = {
        'experiment': experiment,
        'steps': steps,
    }
    return render(request, 'experiment/detail.html', context)


@login_required
def experiment_delete_view(request, experiment_id):
    """删除实验记录的视图"""
    experiment = get_object_or_404(Experiment, id=experiment_id, user=request.user)
    
    if request.method == 'POST':
        # 删除实验记录
        experiment.delete()
        messages.success(request, '实验记录已成功删除！')
        return redirect('experiment_history')
    
    # 如果不是POST请求，重定向到历史记录页面
    return redirect('experiment_history')


@login_required
def knowledge_graph_view(request):
    """知识图谱视图，展示多模态智能螺丝拆卸机器人系统的知识体系"""
    return render(request, 'experiment/knowledge_graph.html')


@login_required
def deepseek_assistant_view(request):
    """处理DeepSeek智能助手的API请求"""
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_message = data.get('message', '')
            
            # DeepSeek API配置
            api_key = 'sk-d7f98fb5f40d4e669906aa439bfa1e74'
            api_url = 'https://api.deepseek.com/v1/chat/completions'
            model = 'deepseek-chat'
            
            # 读取项目内容以提供上下文
            content_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'content.txt')
            project_content = ""
            if os.path.exists(content_path):
                with open(content_path, 'r', encoding='utf-8') as f:
                    project_content = f.read()
            
            # 构建请求体
            headers = {
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {api_key}'
            }
            
            payload = {
                'model': model,
                'messages': [
                    {
                        'role': 'system',
                        'content': f'你是一个智能助手，专门为多模态智能螺丝拆卸机器人系统项目提供支持。以下是项目的详细内容，请基于这些信息回答用户问题。\n\n{project_content}'
                    },
                    {
                        'role': 'user',
                        'content': user_message
                    }
                ],
                'temperature': 0.7,
                'max_tokens': 800
            }
            
            # 发送请求到DeepSeek API
            response = requests.post(api_url, headers=headers, json=payload)
            response_data = response.json()
            
            # 提取助手回复
            assistant_reply = response_data.get('choices', [{}])[0].get('message', {}).get('content', '')
            
            return JsonResponse({
                'reply': assistant_reply
            })
        except Exception as e:
            return JsonResponse({
                'error': str(e)
            }, status=500)
    return JsonResponse({
        'error': 'Only POST requests are allowed'
    }, status=405)
